package com.sunday.shoufen.base;

import android.util.Log;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.sunday.common.utils.SharePerferenceUtils;
import com.sunday.common.utils.ToastUtils;
import com.sunday.shoufen.service.LocationService;

import static com.sunday.common.event.EventBus.TAG;

/**
 * Created by 刘涛 on 2017/10/31.
 */

public abstract class BaseLocFragment extends BaseLazyFragment{

    public LocationService locationService;
    private LocationClient mClient;

    public void requestLocation() {
        locationService = BaseApp.getInstance().getLocationService();
        LocationClientOption mOption = locationService.getDefaultLocationClientOption();
        mOption.setLocationMode(LocationClientOption.LocationMode.Hight_Accuracy);
        mOption.setCoorType("bd09ll");
        mClient = new LocationClient(mContext.getApplicationContext());
        mClient.setLocOption(mOption);
        mClient.registerLocationListener(locListener);
        mClient.start();
    }

    /***
     * 定位结果回调，在此方法中处理定位结果
     */
    BDLocationListener locListener = new BDLocationListener() {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // TODO Auto-generated method stub

            if (location != null && location.getLocType() != BDLocation.TypeServerError) {
                Log.i(TAG, "定位成功");
                Log.i(TAG, "currentThread" + Thread.currentThread());
                mClient.stop();
                String latitude = String.valueOf(location.getLatitude());
                String longitude = String.valueOf(location.getLongitude());
                SharePerferenceUtils.getIns(mContext.getApplicationContext()).putString("latitude", latitude);
                SharePerferenceUtils.getIns(mContext.getApplicationContext()).putString("longitude", longitude);
                BaseApp.getInstance().setCityName(location.getCity());
                BaseApp.getInstance().setLatitude(latitude);
                BaseApp.getInstance().setLongitude(longitude);
                (getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onLocSucceed();
                    }
                });

            } else {
                (getActivity()).runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        onLocSucceed();
                    }
                });
                ToastUtils.showToast(mContext.getApplicationContext(), "定位失败，请开启位置服务后重新定位");
            }
        }

        @Override
        public void onConnectHotSpotMessage(String s, int i) {

        }
    };
    public abstract void onLocSucceed();

    public abstract void onLocFailed();
}
